package com.example.socket.socket.bio.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

public class ChatHandler implements Runnable{

    private CharServer server;

    private Socket socket;

    public ChatHandler(CharServer charServer,Socket socket){
        this.server=charServer;
        this.socket=socket;
    }

    @Override
    public void run() {
        try {

            //存储新上线的用户
            server.addClient(socket);
            //读取用户发送的消息
            BufferedReader reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));

          String msg=null;
            while ((msg=reader.readLine())!=null){
                String fwdMsg="客户端{"+socket.getPort()+"}"+msg+"\n";
                System.out.println(fwdMsg);
                //将消息转发给聊天室里在线的其他用户
                server.forwardMessage(socket,msg+"\n");
                if(server.readyToQuit(msg)){
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                server.removeClient(socket);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
